package com.biz.es.util;

import com.biz.es.config.*;
import lombok.extern.slf4j.*;
import org.apache.commons.lang3.math.*;
import org.apache.http.*;
import org.elasticsearch.client.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.util.*;

/**
 * @Description 加载es资源
 * @Author liuxi
 * @Date 2024/6/10
 **/
@Component
@Slf4j
public class EsRestClient {

    public static Map<String, RestHighLevelClient> clientMap;

    @Resource
    private EsConfigProperties esConfigProperties;

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    @PostConstruct
    public void initialize() {
        List<EsClusterConfig> esConfigs = esConfigProperties.getEsConfigs();
        for (EsClusterConfig esConfig : esConfigs) {
            log.info("initialize config.name:{}, config.node:{}", esConfig.getName(), esConfig.getNodes());
            RestHighLevelClient restHighLevelClient = initRestClient(esConfig);
            clientMap.put(esConfig.getName(), restHighLevelClient);
        }
    }

    private RestHighLevelClient initRestClient(EsClusterConfig esClusterConfig) {
        String[] ipPortArr = esClusterConfig.getNodes().split(",");
        List<HttpHost> httpHostList = new ArrayList<>(ipPortArr.length);
        for (String ipPort : ipPortArr) {
            String[] ipPortInfo = ipPort.split(":");
            if (ipPortInfo.length == 2) {
                HttpHost httpHost = new HttpHost(ipPortInfo[0], NumberUtils.toInt(ipPortInfo[1]));
                httpHostList.add(httpHost);
            }
        }
        HttpHost[] httpHosts = new HttpHost[httpHostList.size()];
        httpHostList.toArray(httpHosts);

        RestClientBuilder builder = RestClient.builder(httpHosts);
        return new RestHighLevelClient(builder);
    }

    public static RestHighLevelClient getClient(String clusterName) {
        return clientMap.get(clusterName);
    }

}
